package com.zdkj.subway.check.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.core.constant.SecurityConstants;
import com.zdkj.common.core.exception.CheckedException;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zdkj.subway.check.dto.SwMessageDTO;
import com.zdkj.subway.check.entity.SwAuConductorNotice;
import com.zdkj.subway.check.entity.SwParamStation;
import com.zdkj.subway.check.enums.MessageEnums;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.fegin.SupportService;
import com.zdkj.subway.check.mapper.SwAuConductorNoticeMapper;
import com.zdkj.subway.check.mapper.SwParamStationMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;


import javax.annotation.Resource;
import java.util.*;
/**
 * 线网层级确认-售票员票款差异确认-售票员票款差异确认通知
 * SW_AU_CONDUCTOR_NOTICE
 */
@Service
public class SwAuConductorNoticeService {

    @Resource
    private SwAuConductorNoticeMapper swAuConductorNoticeMapper;
	@Resource
    private SysUserMapper sysUserMapper;

    @Autowired
    private SupportService supportService;

    @Autowired
    private SwParamStationMapper swParamStationMapper;

    /**
     * 售票员票款差异通知 列表
     * @param jsonObject
     * @return
     */
    public Result getSwAuConductorNoticeList(JSONObject jsonObject) {
        //售票员id
        Integer conductorPersonId = jsonObject.getInteger("conductorPersonId");
        String conductorPersonName = jsonObject.getString("conductorPersonName");//售票员姓名
        String isDifferenceAmount = jsonObject.getString("isDifferenceAmount");//长短款标识
        Integer sendStatus = jsonObject.getInteger("sendStatus");
        //线路站点
        String lineCode = jsonObject.getString("lineCode");
        String stationCode = jsonObject.getString("stationCode");
        //申诉状态
        String appealStatus = jsonObject.getString("appealStatus");
        //收入时间
        Date startTime = jsonObject.getDate("startTime");
        Date endTime = jsonObject.getDate("endTime");

        //流程状态
        String auditSate = jsonObject.getString("auditSate");

        //申诉时间
        Date startSendTime = jsonObject.getDate("startSendTime");
        Date endSendTime = jsonObject.getDate("endSendTime");
        //分页
        Integer startPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");
        Example example = new Example(SwAuConductorNotice.class);
        example.setOrderByClause("RECORD_TIME desc");
        Example.Criteria criteria = example.createCriteria();
        if (conductorPersonId != null) {
            criteria.andEqualTo("conductorPersonId", conductorPersonId);
        }
        if (!StringUtils.isEmpty(conductorPersonName)) {
            criteria.andLike("conductorPersonName", conductorPersonName);
        }
        if (!StringUtils.isEmpty(appealStatus)) {
            criteria.andEqualTo("appealStatus", appealStatus);
        }
        if (!StringUtils.isEmpty(sendStatus)) {
            criteria.andEqualTo("sendStatus", sendStatus);
        }
        if (startTime != null && endTime != null) {
            criteria.andBetween("recordTime",startTime,endTime);
        }
        if (startSendTime != null && endSendTime != null) {
            criteria.andBetween("sendTime",startSendTime,endSendTime);
        }
        if (!StringUtils.isEmpty(lineCode)) {
            criteria.andEqualTo("lineCode", lineCode);
        }
        if (!StringUtils.isEmpty(stationCode)) {
            criteria.andEqualTo("stationCode", stationCode);
        }
	    if(StringUtils.isEmpty(lineCode)) {
            PigxUser user = SecurityUtils.getUser();
            Map<String, Object> p1 = new HashMap<>();
            p1.put("user_code", user.getUserCode());
            List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
            SysUser sysUser = sysUsers.get(0);
            String managementLineStation = sysUser.getManagementLineStation();
            //管辖线路
            if (!StringUtils.isEmpty(managementLineStation)) {
                JSONArray managementLineStations = JSONArray.parseArray(managementLineStation);
                List<String> LineObjects = new ArrayList<>();
                for (int i = 0; i < managementLineStations.size(); i++) {
                    JSONObject jsonObject1 = managementLineStations.getJSONObject(i);
                    lineCode = jsonObject1.getString("line");
                    LineObjects.add(lineCode);
                }
                criteria.andIn("lineCode", LineObjects);
            }else {
                //不管辖线路
                criteria.andEqualTo("lineCode", sysUser.getLineCode());
            }
        }
        if (!StringUtils.isEmpty(isDifferenceAmount)) {
            if("1".equals(isDifferenceAmount)){
                criteria.andGreaterThan("differenceAmount", 0);
            }else {
                criteria.andLessThan("differenceAmount", 0);
            }
        }
        if (!StringUtils.isEmpty(auditSate)) {
            criteria.andEqualTo("auditSate", auditSate);
        }
        PageHelper.startPage(startPage,pageSize);
        List<SwAuConductorNotice> swAuConductorNotices = swAuConductorNoticeMapper.selectByExample(example);

        PageInfo<SwAuConductorNotice> swAuConductorNoticePageInfo = new PageInfo<>(swAuConductorNotices);
        JSONObject resultJson = new JSONObject();
        resultJson.put("list",swAuConductorNotices);
        resultJson.put("pageInfo",swAuConductorNoticePageInfo);
        return new Result(ResultDetailMsg.OK,resultJson);
    }

    /**
     * 售票员票款差异通知 单独查询
     * @param jsonObject
     * @return
     */
    public Result getSwAuConductorNotice(JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        SwAuConductorNotice swAuConductorNotice = swAuConductorNoticeMapper.selectByPrimaryKey(id);
        JSONObject resultJson = new JSONObject();
        resultJson.put("obj",swAuConductorNotice);
        return new Result(ResultDetailMsg.OK,resultJson);
    }

    /**
     * 售票员票款差异通知 申诉
     * @param jsonObject
     * @return
     */
    public Result updateSwAuConductorNotice(JSONObject jsonObject) {
        SwAuConductorNotice swAuConductorNotice =
                JSONObject.parseObject(jsonObject.toJSONString(), SwAuConductorNotice.class);
        int i = swAuConductorNoticeMapper.updateById(swAuConductorNotice);
        return new Result(ResultDetailMsg.OK);
    }

    public Result subAuditSwAuConductorNotice(Integer id) {
        PigxUser user = SecurityUtils.getUser();
        SwAuConductorNotice swAuConductorNotice = swAuConductorNoticeMapper.selectById(id);
        QueryWrapper<SwParamStation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CODE", swAuConductorNotice.getStationCode());
        SwParamStation swParamStation = swParamStationMapper.selectOne(queryWrapper);

        UpdateWrapper<SwAuConductorNotice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("ID", id);
        updateWrapper.set("AUDIT_SATE", 4);
        swAuConductorNoticeMapper.update(null, updateWrapper);

        SwMessageDTO swMessageDTO = new SwMessageDTO();
        swMessageDTO.setTitle(swParamStation.getName() +"："+ swAuConductorNotice.getConductorPersonName()+ "：" +" 售票员票款差异确认通知");
        swMessageDTO.setMsgType("审批");
        swMessageDTO.setCreatorName(user.getNikeName());
        swMessageDTO.setCreatorId(user.getId());
        swMessageDTO.setLineCode(swAuConductorNotice.getLineCode());
        swMessageDTO.setStationCode(swAuConductorNotice.getStationCode());
        swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_CONDUCTOR_NOTICE_URL.getUrl());
        swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
        swMessageDTO.setContent("车站提交，站长待审核");
        supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);

        return new Result(ResultDetailMsg.OK);
    }

    public Result stationMasterAuditSwAuConductorNotice(SwAuConductorNotice swAuConductorNotice) {
        PigxUser user = SecurityUtils.getUser();

        SwAuConductorNotice conductorNotice = swAuConductorNoticeMapper.selectById(swAuConductorNotice.getId());

        QueryWrapper<SwParamStation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CODE", conductorNotice.getStationCode());
        SwParamStation swParamStation = swParamStationMapper.selectOne(queryWrapper);

        SwMessageDTO swMessageDTO = new SwMessageDTO();
        swMessageDTO.setTitle(swParamStation.getName() +"："+ conductorNotice.getConductorPersonName()+ "：" +" 售票员票款差异确认通知");
        swMessageDTO.setMsgType("审批");
        swMessageDTO.setCreatorName(user.getNikeName());
        swMessageDTO.setCreatorId(user.getId());

        UpdateWrapper<SwAuConductorNotice> updateWrapper = new UpdateWrapper<>();
        if (swAuConductorNotice.getAuditSate().equals("6")) {
            if (StringUtils.isEmpty(swAuConductorNotice.getAuditStationOpinion())) {
                throw new CheckedException("驳回请输入审核意见！");
            }
            updateWrapper.set("APPEAL_STATUS", "1");
            updateWrapper.set("AUDIT_STATION_OPINION", swAuConductorNotice.getAuditStationOpinion());
        }
        if (swAuConductorNotice.getAuditSate().equals("8")) {
            if (StringUtils.isEmpty(swAuConductorNotice.getAuditWorkshopOpinion())) {
                throw new CheckedException("驳回请输入审核意见！");
            }
            updateWrapper.set("AUDIT_WORKSHOP_OPINION", swAuConductorNotice.getAuditWorkshopOpinion());
        }
        if (swAuConductorNotice.getAuditSate().equals("10")) {
            if (StringUtils.isEmpty(swAuConductorNotice.getAuditDeptOpinion())) {
                throw new CheckedException("驳回请输入审核意见！");
            }
            updateWrapper.set("AUDIT_DEPT_OPINION", swAuConductorNotice.getAuditDeptOpinion());
        }
        if (swAuConductorNotice.getAuditSate().equals("5") || swAuConductorNotice.getAuditSate().equals("6")) {
            if (!StringUtils.isEmpty(swAuConductorNotice.getAuditStationOpinion())) {
                updateWrapper.set("AUDIT_STATION_OPINION", swAuConductorNotice.getAuditStationOpinion());
            }
            updateWrapper.set("AUDIT_STATION_JOB_NO", user.getUserCode());
            updateWrapper.set("AUDIT_STATION_NAME", user.getNikeName());
            updateWrapper.set("AUDIT_STATION_TIME", new Date());
            if (swAuConductorNotice.getAuditSate().equals("5")) {
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("站长审核通过，车间票务专业待审核");
            } else {
                swMessageDTO.setLineCode(conductorNotice.getLineCode());
                swMessageDTO.setStationCode(conductorNotice.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setContent("站长驳回");
            }
        }

        if (swAuConductorNotice.getAuditSate().equals("7") || swAuConductorNotice.getAuditSate().equals("8")) {
            if (!StringUtils.isEmpty(swAuConductorNotice.getAuditWorkshopOpinion())) {
                updateWrapper.set("AUDIT_WORKSHOP_OPINION", swAuConductorNotice.getAuditWorkshopOpinion());
            }
            updateWrapper.set("AUDIT_WORKSHOP_JOB_NO", user.getUserCode());
            updateWrapper.set("AUDIT_WORKSHOP_NAME", user.getNikeName());
            updateWrapper.set("AUDIT_WORKSHOP_TIME", new Date());
            if (swAuConductorNotice.getAuditSate().equals("7")) {
                swMessageDTO.setDeptId(MessageEnums.AUDIT_DEPT_ID.getCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.PWGLJSRY_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业审核通过，部门票务专业待审核");
            } else {
                swMessageDTO.setLineCode(conductorNotice.getLineCode());
                swMessageDTO.setStationCode(conductorNotice.getStationCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.STATION_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZXZZ_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("车间票务专业驳回，站长待审核");
            }
        }

        if (swAuConductorNotice.getAuditSate().equals("9") || swAuConductorNotice.getAuditSate().equals("10")) {
            if (!StringUtils.isEmpty(swAuConductorNotice.getAuditDeptOpinion())) {
                updateWrapper.set("AUDIT_DEPT_OPINION", swAuConductorNotice.getAuditDeptOpinion());
            }
            updateWrapper.set("AUDIT_DEPT_JOB_NO", user.getUserCode());
            updateWrapper.set("AUDIT_DEPT_NAME", user.getNikeName());
            updateWrapper.set("AUDIT_DEPT_TIME", new Date());
            if (swAuConductorNotice.getAuditSate().equals("9")) {
                swMessageDTO.setDeptId(MessageEnums.AUDIT_DEPT_ID.getCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.AUDIT_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.SYSHJSRY_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("部门票务专业审核通过");
            } else {
                swMessageDTO.setDeptId(MessageEnums.WORKSHOP_DEPT_ID.getCode());
                swMessageDTO.setUrl(MessageEnums.MessageUrlEnums.DEPT_CONDUCTOR_NOTICE_URL.getUrl());
                swMessageDTO.setRoleCode(MessageEnums.ZWPWGL_ROLE_CODE.getCode().toString());
                swMessageDTO.setContent("部门票务专业驳回，车间票务专业待审核");
            }
        }

        updateWrapper.set("AUDIT_SATE", swAuConductorNotice.getAuditSate());
        updateWrapper.eq("ID", swAuConductorNotice.getId());
        swAuConductorNoticeMapper.update(null, updateWrapper);

        supportService.saveInner(swMessageDTO, SecurityConstants.FROM_IN);

        return new Result(ResultDetailMsg.OK);
    }
}
